# _*_ coding:utf-8 _*_
# @File  : examine.py
# @Time  : 2021-12-23  10:50
# @Author: zizle


from fastapi import APIRouter, Query, Depends

from interfaces.depends import logged_require
from db import FAConnection
from status import r_status
from category import VARIETY_NAME


plan_examine_api = APIRouter()


# 查询投资方案数据
@plan_examine_api.get('/')
async def query_exchange_plan(person: dict = Depends(logged_require),
                              level: int = Query(-1, ge=-1), ret: int = Query(-1, ge=-1),
                              page: int = Query(1, ge=1), page_size: int = Query(1, ge=1)):

    query_sql = 'SELECT a.id,a.create_time,a.active_date,a.expire_date,a.title,a.category,a.varieties,a.apply_firm,' \
                'a.examine_level,a.level_explain,a.examine_ret,a.ret_explain,a.creator,a.group_name,a.filepath,' \
                'a.plan_profit,' \
                'u.admin_name ' \
                'FROM exchange_plan AS a ' \
                'INNER JOIN user_user AS u ON a.creator=u.id ' \
                'WHERE a.is_delete=0 ' \
                'ORDER BY a.create_time DESC;'
    # 查询结果，处理数据
    db_conn = FAConnection()
    records = db_conn.query(query_sql)
    if level == 0:  # 未评级的
        records = list(filter(lambda x: x['examine_level'] == 0, records))
    if level == 1:  # 已评级的
        records = list(filter(lambda x: x['examine_level'] > 0, records))

    if ret == 0:  # 未审批的
        records = list(filter(lambda x: x['examine_ret'] == 0, records))
    if ret == 1:  # 已审批的
        records = list(filter(lambda x: x['examine_ret'] > 0, records))

    # 处理分页
    start, offset = (page - 1) * page_size, page_size
    ret_records = records[start: start+page_size]
    total_page = (len(records) + page_size - 1) // page_size

    level_texts = {1: '一级', 2: '二级', 3: '三级', 4: '四级', 5: '五级'}
    ret_texts = {1: '展示', 2: '实盘', 3: '外发'}
    for item in ret_records:
        item['create_time'] = item['create_time'].strftime('%Y-%m-%d %H:%M:%S')
        item['active_date'] = item['active_date'].strftime('%Y-%m-%d')
        item['expire_date'] = item['expire_date'].strftime('%Y-%m-%d')
        item['variety'] = ','.join([VARIETY_NAME.get(i, i) for i in item['varieties'].split(',')])
        item['firm_text'] = '是' if item['apply_firm'] else '否'
        item['level_text'] = '' if item['examine_level'] == 0 else level_texts.get(item['examine_level'], '未知')
        item['ret_text'] = '' if item['examine_ret'] == 0 else ret_texts.get(item['examine_ret'], '未知')

    response_data = {'page': page, 'page_size': page_size, 'total_page': total_page, 'plans': ret_records}

    return {'code': r_status.SUCCESS, 'message': '查询成功!', 'data': response_data}
